package com.wjm.androidnetproclient;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class HttpURLConnectionActivity extends AppCompatActivity {
    private EditText et_spec;
    private Button btn_HttpURLConnection_get;
    private Button btn_HttpURLConnection_post;
    private TextView tv_result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_urlconnection);
        findViewById();
    }

    private void findViewById() {
        et_spec = findViewById(R.id.et_spec);
        btn_HttpURLConnection_get = findViewById(R.id.btn_HttpURLConnection_get);
        btn_HttpURLConnection_post = findViewById(R.id.btn_HttpURLConnection_post);
        tv_result = findViewById(R.id.tv_result);
        btn_HttpURLConnection_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                URLConnectionThread_Get();
            }
        });
        btn_HttpURLConnection_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                URLConnectionThread_Post();
            }
        });
    }

    private void URLConnectionThread_Post() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URLConnection_Post_Test1();
//                URLConnection_Post_Test();//写得不好，废弃
            }
        }).start();
    }

    /**
     * URLConnection Post
     */
    private void URLConnection_Post_Test1() {

    }

    private void URLConnectionThread_Get() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URLConnection_Get_Test();
            }
        }).start();
    }

    private void URLConnection_Post_Test() {
        try {
            String spec = et_spec.getText().toString().trim();
            URL url = new URL(spec);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setConnectTimeout(5000);//5秒超时
            //设置输入和输出流
            httpURLConnection.setDoOutput(true);//报错？
            httpURLConnection.setDoInput(true);//报错？
//设置请求方式为POST
            httpURLConnection.setRequestMethod("POST");
//POST请求不能使用缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setInstanceFollowRedirects(true);
            // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的（设置头更多参数参考：https://blog.csdn.net/kieven2008/article/details/8210737）
            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            // 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
            // 要注意的是connection.getOutputStream会隐含的进行connect。
            httpURLConnection.connect();

            //DataOutputStream流
            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
            //要上传的参数
            String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");//服务端输出：par=ABCDEFG
            //将要上传的内容写入流中
            out.writeBytes(content);
            //刷新、关闭
            out.flush();
//关闭连接
//            httpURLConnection.disconnect();
            if (httpURLConnection.getResponseCode() != 200) {
                //得到读取的内容(流)
//                InputStreamReader in = new InputStreamReader(httpURLConnection.getInputStream());
                // 为输出创建BufferedReader
                BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String inputLine = null;
                //使用循环来读取获得的数据
                StringBuilder sb = new StringBuilder();
                while (((inputLine = br.readLine()) != null)) {
                    //我们在每一行后面加上一个"\n"来换行
                    sb.append(inputLine + "\n");
                }
                //关闭InputStreamReader
                br.close();
                //关闭http连接
                httpURLConnection.disconnect();
                String sbStr = sb.toString();
                refreshUI(sbStr);

            } else {
                String sbStr = httpURLConnection.getResponseCode()+"";
                refreshUI(sbStr);
            }

            //更新UI



        } catch (MalformedURLException e) {
            e.printStackTrace();
            refreshUI(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            refreshUI(e.toString());
        }
    }

    private void URLConnection_Get_Test() {
        try {
            String spec = et_spec.getText().toString().trim();
            URL url = new URL(spec);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            httpURLConnection.setConnectTimeout(5000);//5秒超时
            //设置输入和输出流
//            httpURLConnection.setDoOutput(true);//报错？要在connect之前
//            httpURLConnection.setDoInput(true);报错？
//设置请求方式为POST
            httpURLConnection.setRequestMethod("GET");
//            httpURLConnection.setRequestMethod("POST");
//POST请求不能使用缓存
//            httpURLConnection.setUseCaches(false);
//关闭连接
//            httpURLConnection.disconnect();
            if (httpURLConnection.getResponseCode() != 200) {
                //得到读取的内容(流)
//                InputStreamReader in = new InputStreamReader(httpURLConnection.getInputStream());
                // 为输出创建BufferedReader
                BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String inputLine = null;
                //使用循环来读取获得的数据
                StringBuilder sb = new StringBuilder();
                while (((inputLine = br.readLine()) != null)) {
                    //我们在每一行后面加上一个"\n"来换行
                    sb.append(inputLine + "\n");
                }
                //关闭InputStreamReader
                br.close();
                //关闭http连接
                httpURLConnection.disconnect();
                String sbStr = sb.toString();
                refreshUI(sbStr);

            } else {
                String sbStr = httpURLConnection.getResponseCode()+"";
                refreshUI(sbStr);
            }

            //更新UI



        } catch (MalformedURLException e) {
            e.printStackTrace();
            refreshUI(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            refreshUI(e.toString());
        }
    }

    private void refreshUI(final String result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(result)) {
                    tv_result.setText(result);
                }
            }
        });
    }
}
